﻿using pingjia.bll;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class sp2 : System.Web.UI.Page
{
    private ConsumerService consumerService = new ConsumerService();

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox masterCheckBox = sender as CheckBox;
        if (masterCheckBox != null)
        {
            var gridViewData = GetGridViewData();
            consumerService.ToggleCheckBoxes(gridViewData, masterCheckBox.Checked);
            UpdateGridView(gridViewData);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        var gridViewData = GetGridViewData();
        var selectedProductIds = consumerService.GetSelectedProductIds(gridViewData);
        Label1.Attributes.Add("style", "color: white;");
        Label1.Text = "你选择的ProductID为：" + string.Join("、", selectedProductIds);
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            try
            {
                string productName = e.Row.Cells[3].Text;
                LinkButton deleteButton = e.Row.Cells[8].Controls[0] as LinkButton;
                if (deleteButton != null)
                {
                    deleteButton.OnClientClick = consumerService.GetDeleteConfirmationMessage(productName);
                }
            }
            catch
            {
                // 有异常不做任何操作
            }
        }
    }

    private List<GridViewRowData> GetGridViewData()
    {
        var gridViewData = new List<GridViewRowData>();
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox checkBox = row.FindControl("CheckBox1") as CheckBox;
            if (checkBox != null)
            {
                var rowData = new GridViewRowData
                {
                    ProductId = row.Cells[1].Text,
                    ProductName = row.Cells[3].Text,
                    IsChecked = checkBox.Checked
                };
                gridViewData.Add(rowData);
            }
        }
        return gridViewData;
    }

    private void UpdateGridView(List<GridViewRowData> gridViewData)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox checkBox = row.FindControl("CheckBox1") as CheckBox;
            if (checkBox != null)
            {
                var rowData = gridViewData.Find(data => data.ProductId == row.Cells[1].Text);
                if (rowData != null)
                {
                    checkBox.Checked = rowData.IsChecked;
                }
            }
        }
    }
}